package com.sunlee.admin.api.module.job.task;

import com.sunlee.admin.api.module.job.dto.CrawlerPptCategoryDTO;
import com.sunlee.admin.api.module.job.template.CrawResourceCategoryTemplate;
import com.sunlee.admin.api.module.job.template.TemplateFactory;
import com.sunlee.admin.api.module.job.template.context.CrawResourceCategoryContext;
import com.sunlee.common.core.enums.ErrorCodeEnum;
import com.sunlee.common.core.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 爬取第三方PPT全部分类
 *
 * @author sunlee
 */
@Component("crawlerResourceCategoryTask")
public class CrawlerResourceCategoryTask implements ITask {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    private static boolean isRun = false;

    @Override
    public void run(String params) {
        logger.info("crawlerResourceCategoryTask定时任务正在执行，参数为：{}", params);

        if (isRun) {
            throw new BusinessException("不可重复执行");
        }

        isRun = true;

        try {
            start(validaDTO(params));
        } finally {
            isRun = false;
            logger.info("crawlerResourceCategoryTask定时任务执行结束");
        }
    }

    private void start(CrawlerPptCategoryDTO dto) {
        // 通过来源获取对应模板
        CrawResourceCategoryTemplate categoryTemplate = TemplateFactory.getCrawResourceCategoryTemplateByCode(dto.getSource());
        if (Objects.isNull(categoryTemplate)) {
            return;
        }

        // 构建上下文
        CrawResourceCategoryContext crawResourceCategoryContext = new CrawResourceCategoryContext();

        // 开始执行
        categoryTemplate.process(crawResourceCategoryContext);
    }


    private CrawlerPptCategoryDTO validaDTO(String params) {
        CrawlerPptCategoryDTO dto = validaParseParam(params, CrawlerPptCategoryDTO.class);
        if (Objects.isNull(dto.getSource()) || dto.getSource() < 0) {
            throw new BusinessException(ErrorCodeEnum.PARAM_NOT_COMPLETE);
        }
        return dto;
    }
}
